package gp_fifo_generator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class Generator {
	private static String configFileName = "../design_configuration.ini";
	private static String fileSuffix = ".template";
	
	public static void main(String[] args){
		System.out.println("Hello Gp Fifo Generator!");
		
		Parameters param = new Parameters();
		param.initFromFile(configFileName);
		List<String> files = param.fileList;
		Map<String, String> parameters = param.paramHash;
		
		processAllFiles(files, parameters);
		System.out.println("The End");
	}
	
	private static void processAllFiles(List<String> files, Map<String, String> parameters){
		for(String filename : files){
			System.out.println("Processing file " + filename);
			processFile(filename, parameters);
		}
	}
	
	private static void processFile(String filename, Map<String, String> parameters){
	      try{
	    	 BufferedReader br = new BufferedReader( new FileReader(filename + fileSuffix));
	    	 BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
	         String line;
	         while(( line = br.readLine()) != null ) {
	        	 for(String parameter : parameters.keySet()){
	        		 String parameterPlaceholder = "{"+parameter+"}";
	        		 if (line.contains(parameterPlaceholder)){
	        			 line = line.replace(parameterPlaceholder, parameters.get(parameter));
	        			 System.out.println("\tUpdating line :::" + line);
	        		 }
	        	 }
	        	 bw.write(line + "\n");
	         }
	         br.close();
	         bw.close();
	      }catch(IOException e){
	    	  System.out.println("Template file not found or can't write output file: " + filename);
	      }

	}
}

